package com.ms.service.module.commonsettings;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;

import com.xpec.c4.db.hibernate.manager.HibernateManager;

public class CommonSettingsDAO {

	private static final Log log = LogFactory.getLog(CommonSettingsDAO.class);
	
	/**
	 * 讀取所有共用設定
	 */
	public static List<CommonSettingsModel> loadAllSettings(){
		
		if(log.isInfoEnabled()){
			log.info("loadAllSettingsAfterCheck start!!!");
		}
		
		Session session = HibernateManager.txBegin();
		@SuppressWarnings("unchecked")
		List<CommonSettingsModel> result = session.createQuery("from CommonSettingsModel").list();
		HibernateManager.txCommitFailRollbackClearSession();
		
		return result;
	}
	
	/**
	 * 儲存或更新共用設定
	 */
	public static boolean saveOrUpdateCommonSetting(CommonSettingType type, String settingContent){
		
		Date currentTime = new Date();
		
		Session session = HibernateManager.txBegin();
		CommonSettingsModel model = (CommonSettingsModel) session.createQuery("from CommonSettingsModel where settingType = :TYPE").setParameter("TYPE", type).uniqueResult();
		
		if(model == null){
			model = new CommonSettingsModel();
			model.setSettingType(type);
			model.setCreateTime(currentTime);
			model.setModifyTime(currentTime);
			model.setSettingContent(settingContent);
			session.save(model);
		}
		else{
			model.setModifyTime(currentTime);
			model.setSettingContent(settingContent);
			session.update(model);
		}
		
		return HibernateManager.txCommitFailRollbackClearSession();
	}
	
}
